from machine import I2S
from machine import Pin
import urequests
import network
import time


# 初始化引脚定义
sck_pin = Pin(12)  # 串行时钟输出
ws_pin = Pin(14)   # 字时钟
sd_pin = Pin(13)   # 串行数据输出


def init_audio_out1():
    """初始化 audio_out 对象"""
    return I2S(1,
               sck=sck_pin,
               ws=ws_pin,
               sd=sd_pin,
               mode=I2S.TX,
               bits=16,
               format=I2S.MONO,
               rate=28000,  # 根据实际需要调整采样率
               ibuf=20000)


def init_audio_out2():
    """初始化 audio_out2 对象"""
    return I2S(1,
               sck=sck_pin,
               ws=ws_pin,
               sd=sd_pin,
               mode=I2S.TX,
               bits=16,
               format=I2S.MONO,
               rate=32000,  # 根据实际需要调整采样率
               ibuf=20000)


def playwav(response):
    # 初始化 audio_out
    audio_out = init_audio_out1()

    response.raw.read(44)  # 跳过开头的44字节音频文件头信息

    print("开始播放音频...")

    # 并将其写入I2S DAC
    while True:
        try:
            content_byte = response.raw.read(1024)  # 每次读取1024个字节

            # 判断WAV文件是否结束
            if len(content_byte) == 0:
                break
            # 调用I2S对象播放音频
            audio_out.write(content_byte)

        except Exception as ret:
            print("程序产生异常...", ret)
            if 'audio_out' in locals():
                audio_out.deinit()
            break
    if 'audio_out' in locals():
        audio_out.deinit()  # 音乐播放完毕后，退出


def playwavfile(wavtempfile):
    # 初始化 audio_out2
    audio_out2 = init_audio_out2()

    with open(wavtempfile, 'rb') as f:
        # 跳过文件的开头的44个字节，直到数据段的第1个字节
        pos = f.seek(44)
        # 用于减少while循环中堆分配的内存视图
        wav_samples = bytearray(1024)
        wav_samples_mv = memoryview(wav_samples)
        print("开始播放音频...")

        # 并将其写入I2S DAC
        while True:
            try:
                num_read = f.readinto(wav_samples_mv)

                # WAV文件结束
                if num_read == 0:
                    break

                # 直到所有样本都写入I2S外围设备
                num_written = 0
                while num_written < num_read:
                    num_written += audio_out2.write(wav_samples_mv[num_written:num_read])

            except Exception as ret:
                print("产生异常...", ret)
                break
    # 结束后释放资源
    if 'audio_out2' in locals():
        audio_out2.deinit()


wavtempfile = "audio.wav"
if __name__ == "__main__":
    # 注意不要用https,要用http
    # response = urequests.get("http://doc.itprojects.cn/0006.zhishi.esp32/01.download/audio/chaojimali.wav", stream=True)
    response = urequests.get("http://192.168.1.15:8052", stream=True)
    playwav(response)
